<template>
  <div class="register-container">
    <h1>人脸注册</h1>
    <div class="register-form">
      <div class="form-group">
        <label for="name">姓名</label>
        <input 
          type="text" 
          id="name" 
          v-model="name"
          placeholder="请输入姓名"
          required
        >
      </div>
      
      <div class="form-group">
        <label>上传照片</label>
        <div 
          class="upload-area" 
          :class="{ 'has-image': imagePreview }"
          @click="triggerFileInput"
          @dragover.prevent
          @dragenter.prevent
          @drop.prevent="handleDrop"
        >
          <input 
            ref="fileInput" 
            type="file" 
            accept="image/*" 
            style="display: none"
            @change="handleFileChange"
          >
          
          <div v-if="!imagePreview" class="upload-placeholder">
            <div class="upload-icon">📷</div>
            <p>点击或拖拽图片到此处上传</p>
            <p class="upload-hint">支持 JPG、PNG 格式</p>
          </div>
          
          <div v-else class="image-preview">
            <img :src="imagePreview" alt="预览图片">
            <button class="change-image-btn" @click.stop="triggerFileInput">
              更换图片
            </button>
          </div>
        </div>
      </div>
      
      <button 
        class="register-btn" 
        :disabled="!name || !imagePreview || isLoading"
        @click="handleRegister"
      >
        {{ isLoading ? '注册中...' : '注册' }}
      </button>
      
      <div v-if="message" class="message" :class="messageType">
        {{ message }}
      </div>
    </div>
    
    <div class="tips-section">
      <h3>拍摄提示</h3>
      <ul>
        <li>确保光线充足，避免逆光拍摄</li>
        <li>将人脸完整置于画面中央</li>
        <li>避免遮挡面部特征（如眼镜、口罩等）</li>
        <li>保持自然表情，面向镜头</li>
      </ul>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import axios from 'axios'

const name = ref('')
const imagePreview = ref('')
const fileInput = ref(null)
const isLoading = ref(false)
const message = ref('')
const messageType = ref('success')

// 触发文件选择
const triggerFileInput = () => {
  fileInput.value?.click()
}

// 处理文件选择
const handleFileChange = (event) => {
  const file = event.target.files[0]
  if (file) {
    processImage(file)
  }
}

// 处理拖拽上传
const handleDrop = (event) => {
  const file = event.dataTransfer.files[0]
  if (file) {
    processImage(file)
  }
}

// 处理图片
const processImage = (file) => {
  // 验证文件类型
  if (!file.type.match('image.*')) {
    showMessage('请上传有效的图片文件', 'error')
    return
  }
  
  // 读取图片预览
  const reader = new FileReader()
  reader.onload = (e) => {
    imagePreview.value = e.target.result
  }
  reader.readAsDataURL(file)
}

// 显示消息
const showMessage = (text, type = 'success') => {
  message.value = text
  messageType.value = type
  
  // 3秒后清除消息
  setTimeout(() => {
    message.value = ''
  }, 3000)
}

// 注册人脸
const handleRegister = async () => {
  if (!name.value.trim() || !imagePreview.value) {
    showMessage('请填写姓名并上传照片', 'error')
    return
  }
  
  isLoading.value = true
  const apiBaseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5000/api'
  
  try {
    // 发送注册请求
    const response = await axios.post(`${apiBaseUrl}/register`, {
      name: name.value.trim(),
      image: imagePreview.value
    })
    
    if (response.data.success) {
      showMessage(`注册成功！用户ID: ${response.data.user_id}`)
      // 重置表单
      name.value = ''
      imagePreview.value = ''
    } else {
      showMessage(response.data.error || '注册失败', 'error')
    }
  } catch (error) {
    console.error('注册请求失败:', error)
    
    // 特别处理人脸重复注册的情况
    if (error.response && error.response.status === 409 && error.response.data) {
      const existingUser = error.response.data.existing_user
      if (existingUser) {
        showMessage(`该人脸已注册，用户名为：${existingUser.name}（ID: ${existingUser.id}）`, 'warning')
      } else {
        showMessage('该人脸已注册', 'warning')
      }
    } else {
      // 其他错误处理
      showMessage(error.response?.data?.error || '网络错误，请稍后重试', 'error')
    }
  } finally {
    isLoading.value = false
  }
}
</script>

<style scoped>
.register-container {
  padding: 2rem;
  max-width: 800px;
  margin: 0 auto;
}

.register-container h1 {
  text-align: center;
  margin-bottom: 2rem;
  color: #333;
}

.register-form {
  background: #fff;
  padding: 2rem;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 2rem;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
  color: #555;
}

.form-group input[type="text"] {
  width: 100%;
  padding: 0.8rem;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 1rem;
}

.form-group input[type="text"]:focus {
  outline: none;
  border-color: #4CAF50;
}

.upload-area {
  border: 2px dashed #ccc;
  border-radius: 8px;
  padding: 2rem;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  min-height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-area:hover {
  border-color: #4CAF50;
  background-color: #f9f9f9;
}

.upload-area.has-image {
  border-style: solid;
  border-color: #4CAF50;
}

.upload-placeholder {
  color: #666;
}

.upload-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
}

.upload-hint {
  font-size: 0.9rem;
  color: #999;
  margin-top: 0.5rem;
}

.image-preview {
  position: relative;
  width: 100%;
  max-width: 300px;
  margin: 0 auto;
}

.image-preview img {
  width: 100%;
  height: auto;
  border-radius: 8px;
}

.change-image-btn {
  position: absolute;
  bottom: 10px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(0, 0, 0, 0.7);
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 5px;
  cursor: pointer;
  font-size: 0.9rem;
}

.register-btn {
  width: 100%;
  padding: 0.8rem;
  background: #4CAF50;
  color: white;
  border: none;
  border-radius: 5px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.register-btn:hover:not(:disabled) {
  background: #45a049;
}

.register-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.message {
  padding: 1rem;
  border-radius: 5px;
  margin-top: 1rem;
  text-align: center;
  font-weight: 500;
}

.message.success {
  background-color: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}

.message.error {
  background-color: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}

.message.warning {
  background-color: #fff3cd;
  color: #856404;
  border: 1px solid #ffeaa7;
}

.tips-section {
  background: #f8f9fa;
  padding: 1.5rem;
  border-radius: 8px;
}

.tips-section h3 {
  margin-bottom: 1rem;
  color: #333;
}

.tips-section ul {
  margin: 0;
  padding-left: 1.5rem;
}

.tips-section li {
  margin-bottom: 0.5rem;
  color: #666;
}

@media (max-width: 768px) {
  .register-container {
    padding: 1rem;
  }
  
  .register-form {
    padding: 1.5rem;
  }
  
  .upload-area {
    padding: 1.5rem;
    min-height: 150px;
  }
}
</style>